/**
  * @description: 手机组件
  * @author: hj
  * @update: hj(2020-01-14)
  */

import React, {Component} from 'react';
// import {Table} from '@alifd/next';
import styles from './index.module.scss';
import {getMediaById} from '@/service/Api/Chart';
import { observer,inject,Provider } from 'mobx-react';

let tableTimer;

 
@inject('chartStore') 
@observer


class Phone extends Component {
    constructor(props) {
        super(props);
        this.state = {
            params: [],
            data: [],
            forceFit: true, //forceFit自动试用宽度，默认false
            width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
            height: this.props.data.height ? this.props.data.height : '100%',
            condition: this.props.data.condition ? this.props.data.condition : '',
            pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
            nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
            color: this.props.data.color,
            title: '',
            chartId: this.props.data.chartId,
            id: this.props.data.componentId,
            chartData: [],
            axisArr: {},
            columnMaps:[],
            haveData: false,

            dataNull: false, // 暂无数据

            // 全局变量
            mainData: [], // 操作组件可操作数据
            mainName: '', // 操作组件可操作当前维度
            mainFlag: false, // 是否是操作组件

            // 手机相关数据
            phoneTime: '', // 手机时间
            imgIndex: 0, // 当前手机页面
            phoneWeek: 0, // 限行尾号
        };
        this.btnOnClick = this.btnOnClick.bind(this);
    };


    componentWillMount() { //初始化
        const _this = this;
        
        // 预览界面
        if (_this.state.pageFlag == 'preview') {
            // 判断当前组件是否是可操作组件
            const { globalData } = _this.props.chartStore;
            if (globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == _this.state.chartId) { // 可操作组件
                        let affectName = item.affectDimension;
                        _this.setState({
                            mainFlag: true,
                            mainName: affectName
                        })
                    }
                })
            }

            _this.interfaceRequest(_this.state.chartId,_this.state.condition);
        } else { // 配置面板
            if (_this.state.nofirst == 'nofirst') {
                _this.saveHandleData();
            } else {
                _this.interfaceRequest(_this.state.chartId,_this.state.condition);
            }
        }
    }

    // 钩子函数--组件挂载完成后
    componentDidMount() { //初始化
        this.setState({
            haveData: true
        })
    }
    // 接收父组件的数据改变
    componentWillReceiveProps = (nextProps) => {
        const _this = this;
        const { globalData } = _this.props.chartStore;

        // 预览界面---判断是否是变化组件
        if (nextProps.data.pageFlag == 'preview') {
            if (nextProps.data.condition != this.props.data.condition && globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affectFlag && item.require == nextProps.data.chartId) { // 联动组件
                        let key = item.requireDimension;
                        let condition = {};
                        Object.keys(nextProps.data.condition).forEach(function(keys){
                            condition[key] = nextProps.data.condition[keys];
                        })
                        _this.interfaceRequest(nextProps.data.chartId,condition);
                    }
                })
            }
        }
    }

    // 数据接口请求
    interfaceRequest = (chartId,condition) => {
        let data = {
            charId: chartId,
            condition: condition
        };
        this.getMediaById(data);
    }
    
    // 数据存储刷新
    saveHandleData = () => {
        const { chartArrData } = this.props.chartStore;
        if (chartArrData.slice().length > 0) {
            chartArrData.slice().map((item) => {
                if (item.id == this.state.chartId) {
                    this.setState({
                        haveData: true
                    },function() {
                        // 数据处理
                        this.handleData(item.data);
                    })
                }
            })
        }
    }

    async getMediaById(data) {
        const res = await getMediaById(data);
        if (res.data && res.data.code === 0) {
            let str = res.data;
            if (str.data && str.data.data && str.data.data.length > 0) {
                // 存储图例原始数据
                const { saveChartData } = this.props.chartStore;
                let oldData = {
                    id: this.state.chartId,
                    data: str.data.data
                }
                saveChartData(oldData);

                // 数据处理
                this.handleData(str.data.data);
            } else {
                this.setState({
                    dataNull: true
                })
            }
        } else {
            this.setState({
                dataNull: true
            })
        }
    }
    // 数据处理
    handleData = (storeAllData) => {
        let storeData = storeAllData[0];
        this.setState({
            dataNull: true
        });

        // 存储可操作组件数据
        if (storeData.affect && storeData.affect.length > 0) {
            let obj = {
                id: this.state.chartId,
                label: storeData.title,
                dimensionData: []
            }
            const { saveAffectData } = this.props.chartStore;

            let dimensionData = [];
            storeData.affect.slice().map((item,index) => {
                dimensionData.push(item);
            })
            obj.dimensionData = dimensionData;
            saveAffectData(obj);

            let newNameData = [];
            let mainName = this.state.mainName;
            storeData.data.map((item,index) => {
                Object.keys(item).forEach(function(key){
                    if (key == mainName) {
                        newNameData.push(item[key]);
                    }
                })
            })
            console.log('TableZebra----',newNameData);
            this.setState({
                mainData: newNameData
            })
        }
        // 存储联动组件数据
        if (storeData.requires && storeData.requires.length > 0) {
            let obj = {
                id: this.state.chartId,
                label: storeData.title,
                dimensionData: []
            }
            const { saveRequireData } = this.props.chartStore;

            let dimensionData = [];
            storeData.requires.slice().map((item,index) => {
                dimensionData.push(item);
            })
            obj.dimensionData = dimensionData;
            saveRequireData(obj);
        }


        // 组装当前图例的维度和度量
        let xyArr = [];
        if (storeData.data.length > 0) {
            Object.keys(storeData.data[0]).forEach(function (key) {
                xyArr.push(key)
            });
            if (xyArr.indexOf('index') > -1) {
                let index = xyArr.indexOf('index');
                xyArr.splice(index,1);
                xyArr.unshift('index');
            }
            this.setState({
                dataNull: false
            })
        }

        this.setState({
            title: storeData.title,
            chartData: storeData.data,
            axisArr: xyArr,
            columnMaps:storeData.columnMaps,
            haveData: true
        })
    }

    // 改变全局变量
    onGlobalVariable = (val) => {
        this.props.onGlobalVariable(val);
    }

    // 获取当前系统时间
    getSystemTime = () => {;
        let date =  new Date(),
            hours = date.getHours(),
            minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
        let Week = date.getDay();
            
        let dateTime = hours + ":" + minutes;
        
        this.setState({
            phoneTime: dateTime,
            phoneWeek: Week
        })
    };
    // 点击按钮
    btnOnClick = (index) => {
        this.setState({
            imgIndex: index
        })
    }
    
    



    render() {
        const _this = this;
        let Layer = this.props.layer;
        
        const {haveData} = this.state;
        const {columnMaps} = this.state;
        const {chartData} = this.state;
        const {axisArr} = this.state;
        
        // 实时显示系统时间
        setTimeout(() => {
            setInterval(this.getSystemTime(),60000)
        },1000);

        let imgArr = [0,1,2,3];
        let bgColor = ['#f8bcba','#fff','#ffa3d2','#d79167'];

        let week = new Date().getDay();
        let weekData = [1,2,3,4,5];
        let weekFlag = weekData.indexOf(week) > -1 ? true : false;
        let numData = week == 1 ? [1,6] : 
                    week == 2 ? [2,7] : 
                    week == 3 ? [3,8] : 
                    week == 4 ? [4,9] : 
                    week == 5 ? [5,0] : ['-','-'];

        
        


        return (
            
            <div id={this.state.id+'_'+this.state.chartId} style={{zIndex: 9999,width: this.state.width,height: this.state.height,padding: '18% 15% 17%'}}>
                <Layer width={this.state.width} title={this.state.title} chartId={this.state.chartId} choiceData={this.state.mainData} onGlobalVariable={this.onGlobalVariable}></Layer>
                <div id={'chart_'+this.state.id+'_'+this.state.chartId} className={styles.phoneBox} >
                    <div>
                        <img src={require('./images/'+this.state.imgIndex+'.png')} alt="" />
                        <span className={styles.phoneTime} style={{backgroundColor: bgColor[this.state.imgIndex]}}> {this.state.phoneTime} </span>
                        <div className={styles.phoneBtn}>
                            <ul>
                            {imgArr.map((item,index) => {
                                return (
                                    <li onClick={(e) => this.btnOnClick(index)}></li>
                                )
                            })}
                            </ul>
                        </div>
                        {
                            this.state.imgIndex == 0 &&
                            <div className={styles.phoneNum}>
                                <div>
                                    <p>今日限行尾号</p>
                                    <span style={{left: '45px'}}> {numData[0]} </span>
                                    <span style={{left: '70px'}}> {numData[1]} </span>
                                </div>
                            </div>
                        }
                        {/* {
                            this.state.imgIndex == 0 && !weekFlag && 
                            <div className={styles.phoneNumNull}> -- </div>
                        } */}
                    </div>
                </div>
            </div>
        );
    }


}

export default Phone;

